# -*-coding:utf-8-*-

import time, cookielib, threading, random
import logConfig as log
from protocol import *
from threadCenter import *
from interfaceFunc import *

# 测试平台：tcpapp服务
# 调用方式：多线程，分批次
# 涉及接口：TCP接入接口、TCP心跳接口、进入语音频道接口

# 线程说明：创建压力测试线程的函数
# 测试接口：创建用户、删除用户、HTTP登录、获取所有群组与成员信息、进入群组通道
def thread_PT_getOnlineNumMax(cpu, name, password, index, groupNum, lock):
    try:
        #log.info("Start to create the thread of getOnlineNumMax")
        thread_PT_getOnlineNumMax = threading.Thread(target=intercom_getOnlineNumMax, args=(cpu, name, password, index, groupNum, lock,))
        thread_PT_getOnlineNumMax.start()
    except Exception, e:
        log.error("Error is occur in create thread of getOnlineNumMax" + str(e))

def intercom_getOnlineNumMax(cpu, name, password, index, groupNum, lock):
    username = name+str(index)
    userType = 2
    
    uid = 0
    gid = 0
    defaultGroupId = 0
    groupId = 0
    cmpid = 0
    key = ""
    groupList = ""
    groupListArray = []
    nextflag = 0
    useTime = 0
    websocket = None
    udpsocket = None
    rtpsocket = None
    
    startTime_all = time.time()
    #log.info("Start to send the login request! username"+str(username))
    startTime_httpLogin = time.time()
    response = pressure_fnHttpPost_app(cpu["data"]._const["WS"]["CONFIG"]["HOST"], cpu["data"]._const["HTTP"]["PORT"], '/fn/app/login.do', getLoginMsg(username, password, userType))
    endTime_httpLogin = time.time()
    useTime_httpLogin = endTime_httpLogin - startTime_httpLogin
    #print(str(response))
    if response["status"] == 'success' and response["content"]["status"] == 1000:
        if lock.acquire():
            cpu["data"]._const["PressureTest"]["loginNum"] += 1
            lock.release()
        uid = response["content"]["body"]["userid"]
        cmpid = response["content"]["body"]["companyId"]
        defaultGroupId = response["content"]["body"]["defaultGroupId"]
        key = response["content"]["body"]["userToken"]
        nextflag = 1

    if nextflag == 1:
        #log.info("Start to create the websocket for tcp...")
        websocket = pressure_webSocket(cpu, cpu["data"]._const["WS"]["CONFIG"]["HOST"], cpu["data"]._const["WS"]["CONFIG"]["PORT"], cpu["data"]._const["WS"]["CONFIG"]["PATH"], cmpid, uid, password, key)
        #log.info("Start to send the tcpIn request as 1")
        times = 0
        while True:
            if(websocket.statCon == True):
                websocket.startTime_tcpIn = time.time()
                websocket.wsTcpSend(assemblyTCPData(1, 1, 1, getAccessMsg(cmpid, uid, md5(password), userType, FN_KEY)))
                break
            else:
                if times > cpu["data"]._const["PressureTest"]["maxTimeout"]:
                    return -1
                else:
                    times+=1
                time.sleep(0.001)
        #log.info("Start to send the heartbeat request as 2")
        times = 0
        while True:
            if(websocket.statTcpIn == True):
                websocket.startTime_heart = time.time()
                if lock.acquire():
                    cpu["data"]._const["PressureTest"]["tcpInNum"] += 1
                    lock.release()
                
                websocket.wsTcpSend(assemblyTCPData(2, 1, 0, getHeartBeatMsg(cmpid, uid, websocket.token)))
                break
            else:
                if times > cpu["data"]._const["PressureTest"]["maxTimeout"]:
                    return -1
                else:
                    times+=1
                time.sleep(0.001)
        #log.info("Start to send the heartbeat thread as 2")
        thread_heartbeat = threading.Thread(target=heartbeat, args=(websocket, cmpid, uid, websocket.token))
        thread_heartbeat.start()

        #log.info("Start to send the enter group request as 3")
        times = 0
        while True:
            if(websocket.statHeart == True):
                websocket.startTIme_inChannel = time.time()
                if lock.acquire():
                    cpu["data"]._const["PressureTest"]["heartbeatNum"] += 1
                    lock.release()
                
                websocket.wsTcpSend(assemblyTCPData(3, 1, 1, getInVoiceChannelMsg(cmpid, uid, defaultGroupId, cpu["data"]._const["CHANNEL_TYPE"]["intercom"])))
                break
            else:
                if times > cpu["data"]._const["PressureTest"]["maxTimeout"]:
                    return -1
                else:
                    times+=1
                time.sleep(0.001)

        times = 0
        while True:
            if(websocket.statInChannel == True):
                if lock.acquire():
                    cpu["data"]._const["PressureTest"]["inChannelNum"] += 1
                    lock.release()    
                websocket.endTime_inChannel = time.time()
                endTime_all = time.time()
                useTime_all = endTime_all - startTime_all
                break
            else:
                if times > cpu["data"]._const["PressureTest"]["maxTimeout"]:
                    return -1
                else:
                    times+=1
                time.sleep(0.001)

        #if udpsocket == None:
        #    log.info("aip:"+str(websocket.aip)+" aport:"+str(websocket.aport)+" sid:"+str(websocket.sid)+" cid:"+str(websocket.cid)+" uid:"+str(uid))
        #    udpsocket = udpSocket(websocket.aip, websocket.aport)
        #    rtpData = getRtpPackage(websocket.sid, websocket.cid, uid)
        #    thread_heartbeatRtp = threading.Thread(target=heartbeatRtp, args=(udpsocket, rtpData))
        #    thread_heartbeatRtp.start()
        #time.sleep(5)
        #websocket.wsTcpSend(assemblyTCPData(4, 1, 1, getOutVoiceChannelMsg(cmpid, uid)))

        #log.info(u"耗时计算")
        useTime_creatWS = websocket.endTime_init - websocket.startTime_init
        useTime_tcpIn = websocket.endTime_tcpIn - websocket.startTime_tcpIn
        useTime_heart = websocket.endTime_heart - websocket.startTime_heart
        useTime_inChannel = websocket.endTime_inChannel - websocket.startTIme_inChannel

        if lock.acquire():
            #log.info(u"HTTP登录耗时："+str(useTime_httpLogin)+
            #         u"\tHTTP获取群组与成员信息耗时："+str(useTime_getGroupMember)+
            #         u"\t  创建Websocket耗时："+str(useTime_creatWS)+
            #         u"\tTCP接入状态："+str(websocket.statTcpIn)+
            #         u"\tTCP接入耗时："+str(useTime_tcpIn)+
            #         u"\tTCP心跳状态："+str(websocket.statHeart)+
            #         u"\tTCP心跳耗时："+str(useTime_heart)+
            #         u"\tTCP语音状态："+str(websocket.statInChannel)+
            #         u"\tTCP进入语音频道："+str(useTime_inChannel)+
            #         u"\t进入语音频道总耗时："+str(useTime_all))
            lock.release()
        if cpu["data"]._const["PressureTest"]["timeMin_tcpIn"] == 0:
            cpu["data"]._const["PressureTest"]["timeMin_tcpIn"] = useTime_tcpIn
        elif useTime_tcpIn < cpu["data"]._const["PressureTest"]["timeMin_tcpIn"]:
            cpu["data"]._const["PressureTest"]["timeMin_tcpIn"] = useTime_tcpIn
        if useTime_tcpIn > cpu["data"]._const["PressureTest"]["timeMax_tcpIn"]:
            cpu["data"]._const["PressureTest"]["timeMax_tcpIn"] = useTime_tcpIn

        if cpu["data"]._const["PressureTest"]["timeMin_heart"] == 0:
            cpu["data"]._const["PressureTest"]["timeMin_heart"] =useTime_heart
        elif useTime_heart < cpu["data"]._const["PressureTest"]["timeMin_heart"]:
            cpu["data"]._const["PressureTest"]["timeMin_heart"] = useTime_heart
        if useTime_heart > cpu["data"]._const["PressureTest"]["timeMax_heart"]:
            cpu["data"]._const["PressureTest"]["timeMax_heart"] = useTime_heart

        if cpu["data"]._const["PressureTest"]["timeMin_inChannel"] == 0:
            cpu["data"]._const["PressureTest"]["timeMin_inChannel"] = useTime_inChannel
        elif useTime_inChannel < cpu["data"]._const["PressureTest"]["timeMin_inChannel"]:
            cpu["data"]._const["PressureTest"]["timeMin_inChannel"] = useTime_inChannel
        if useTime_inChannel > cpu["data"]._const["PressureTest"]["timeMax_inChannel"]:
            cpu["data"]._const["PressureTest"]["timeMax_inChannel"] = useTime_inChannel

        if lock.acquire():
            log.info("The login success num is:"+str(cpu["data"]._const["PressureTest"]["loginNum"]))
            log.info("The groupQuery success num is:"+str(cpu["data"]._const["PressureTest"]["groupQueryNum"]))
            log.info("The tcpInNum success num is:"+str(cpu["data"]._const["PressureTest"]["tcpInNum"]))
            log.info("The heartbeatNum num is:"+str(cpu["data"]._const["PressureTest"]["heartbeatNum"]))
            log.info("The inChannelNum num is:"+str(cpu["data"]._const["PressureTest"]["inChannelNum"]))
            #log.info(u"TCP接入：\t" + str(cpu["data"]._const["PressureTest"]["timeMin_tcpIn"]) + "-->" + str(cpu["data"]._const["PressureTest"]["timeMax_tcpIn"]))
            #log.info(u"TCP心跳：\t" + str(cpu["data"]._const["PressureTest"]["timeMin_heart"]) + "-->" + str(cpu["data"]._const["PressureTest"]["timeMax_heart"]))
            #log.info(u"进入语音频道：\t" + str(cpu["data"]._const["PressureTest"]["timeMin_inChannel"]) + "-->" + str(cpu["data"]._const["PressureTest"]["timeMax_inChannel"]))
            lock.release()
